package jam.network.message;

import jam.model.*;
import jam.network.*;
import java.util.*;

//
// =============================================================================
//

public class ClientActionLeave extends ClientCommand {
    protected static final String KEYWORD = "CA_LEAVE";
    private String channelName;
    
    //
    // =========================================================================
    //
    
    /**
     */
    @Override
    public void process(ClientController controller) {
        NetworkController network = controller.getNetworkController();
        ClientModel client = controller.getModel();
        ServerModel server = network.getModel();
        
        // Try and get the channel. Fail if we aren't in that channel.
        Channel channel = client.getChannel(this.channelName);
        if (channel == null) {
            controller.send(new ServerResponse(this, false));
            return;
        }
 
        // Remove us from the channel and remove the channel from the client.
        channel.removeUser(client.getUser().getUsername());
        client.removeChannel(this.channelName);                    
        
        // Alert all users in the channel, except us.
        Set<String> users = channel.getUsers();
        for (String user: users) {
            if (user.equalsIgnoreCase(client.getUser().getUsername()))
                continue;
                
            ClientController userController = server.getLoggedInMap().get(user);                
            userController.send(new ServerActionLeave(
                userController.getNextTransactionId(),
                this.channelName,
                client.getUser().getUsername()));
        } 
        
        // Respond to the first client.
        controller.send(new ServerResponse(this, true));
    }
    
    //
    // =========================================================================
    //
    
    @Override
    protected String getKeyword() { 
        return ClientActionLeave.KEYWORD; 
    }
    
    //
    // =========================================================================
    //
    
    /**
     * Constructor. Processes the data string.
     *
     * @param transactionId The identification number for this particular message.
     * @param args A scanner with the arguments
     */
    protected ClientActionLeave (int transactionId, Scanner args) {
        super(transactionId);
        
        // Read in the message arguments.
        this.channelName = args.next();
    }
}